<template>
  <div class="message-page">
    <div class="header">
      <h2>消息管理</h2>
      <div class="actions">
        <el-button type="primary" @click="handleBatchRead" :disabled="!selectedMessages.length">
          批量标记已读
        </el-button>
      </div>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="消息类型">
          <el-select v-model="filterForm.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="item in messageTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="未读" value="UNREAD" />
            <el-option label="已读" value="READ" />
            <el-option label="已回复" value="REPLIED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table
      :data="messages"
      border
      style="width: 100%; margin-top: 20px;"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <template #empty>
        <div class="empty-block">
          <el-empty
            description="暂无最新消息"
            :image-size="120"
          >
            <template #image>
              <el-icon :size="60" style="color: #909399"><ChatLineRound /></el-icon>
            </template>
            <template #description>
              <p class="empty-text">暂无最新消息</p>
              <p class="empty-sub-text">当有新消息时，将在这里显示</p>
            </template>
          </el-empty>
        </div>
      </template>
      <el-table-column type="selection" width="55" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.type)">
            {{ getTypeName(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
      <el-table-column prop="sender" label="发送者" width="120" />
      <el-table-column prop="createTime" label="发送时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button 
            size="small" 
            type="primary" 
            @click="handleReply(row)"
            v-if="row.status !== 'REPLIED'"
          >
            回复
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      @current-change="handlePageChange"
      style="margin-top: 20px; justify-content: flex-end;"
      layout="total, sizes, prev, pager, next, jumper"
    />

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'view' ? '消息详情' : '回复消息'"
      width="600px"
    >
      <div v-if="currentMessage">
        <div class="message-detail">
          <div class="message-header">
            <el-tag :type="getTagType(currentMessage.type)" style="margin-right: 10px;">
              {{ getTypeName(currentMessage.type) }}
            </el-tag>
            <span class="message-time">{{ currentMessage.createTime }}</span>
          </div>
          <div class="message-content">
            <h4>{{ currentMessage.title }}</h4>
            <p>{{ currentMessage.content }}</p>
          </div>
          <div v-if="currentMessage.reply" class="message-reply">
            <h4>回复内容：</h4>
            <p>{{ currentMessage.reply }}</p>
            <span class="reply-time">回复时间：{{ currentMessage.replyTime }}</span>
          </div>
        </div>
        <el-form v-if="dialogType === 'reply'" :model="replyForm" :rules="replyRules" ref="replyFormRef">
          <el-form-item prop="content" label="回复内容">
            <el-input
              v-model="replyForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            v-if="dialogType === 'reply'" 
            type="primary" 
            @click="submitReply"
            :loading="submitting"
          >
            提交回复
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getMessages, 
  getMessageDetail, 
  replyMessage, 
  markMessageAsRead,
  batchMarkAsRead,
  MESSAGE_TYPES,
  MESSAGE_STATUS
} from '@/api/message'

// 消息类型选项
const messageTypes = [
  { value: MESSAGE_TYPES.PRE_SALE, label: '售前咨询' },
  { value: MESSAGE_TYPES.AFTER_SALE, label: '售后咨询' },
  { value: MESSAGE_TYPES.SYSTEM, label: '系统消息' }
]

// 筛选表单
const filterForm = ref({
  type: '',
  status: ''
})

// 分页
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 消息列表
const messages = ref([])
const loading = ref(false)
const selectedMessages = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('view') // 'view' 或 'reply'
const currentMessage = ref(null)
const replyFormRef = ref(null)
const submitting = ref(false)

// 回复表单
const replyForm = reactive({
  content: ''
})

// 回复表单验证规则
const replyRules = {
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
  ]
}

// 获取类型名称
const getTypeName = (type) => {
  const found = messageTypes.find(item => item.value === type)
  return found ? found.label : type
}

// 获取标签类型
const getTagType = (type) => {
  switch (type) {
    case MESSAGE_TYPES.PRE_SALE: return 'success'
    case MESSAGE_TYPES.AFTER_SALE: return 'warning'
    case MESSAGE_TYPES.SYSTEM: return 'info'
    default: return ''
  }
}

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    [MESSAGE_STATUS.UNREAD]: '未读',
    [MESSAGE_STATUS.READ]: '已读',
    [MESSAGE_STATUS.REPLIED]: '已回复'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case MESSAGE_STATUS.UNREAD: return 'danger'
    case MESSAGE_STATUS.READ: return 'info'
    case MESSAGE_STATUS.REPLIED: return 'success'
    default: return ''
  }
}

// 获取消息列表
const fetchMessages = async () => {
  try {
    loading.value = true
    const params = {
      ...filterForm.value,
      page: pagination.value.current,
      size: pagination.value.size
    }
    const { data } = await getMessages(params)
    messages.value = data.list
    pagination.value.total = data.total
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchMessages()
}

// 重置搜索
const resetSearch = () => {
  filterForm.value = {
    type: '',
    status: ''
  }
  handleSearch()
}

// 分页变化
const handlePageChange = () => {
  fetchMessages()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedMessages.value = selection
}

// 批量标记已读
const handleBatchRead = async () => {
  if (!selectedMessages.value.length) return
  
  try {
    const ids = selectedMessages.value.map(msg => msg.id)
    await batchMarkAsRead(ids)
    ElMessage.success('标记成功')
    fetchMessages()
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('批量标记已读失败')
  }
}

// 查看消息
const handleView = async (row) => {
  try {
    const { data } = await getMessageDetail(row.id)
    currentMessage.value = data
    dialogType.value = 'view'
    dialogVisible.value = true
    
    // 如果消息未读，标记为已读
    if (row.status === MESSAGE_STATUS.UNREAD) {
      await markMessageAsRead(row.id)
      row.status = MESSAGE_STATUS.READ
    }
  } catch (error) {
    console.error('获取消息详情失败:', error)
    ElMessage.error('获取消息详情失败')
  }
}

// 回复消息
const handleReply = async (row) => {
  try {
    const { data } = await getMessageDetail(row.id)
    currentMessage.value = data
    dialogType.value = 'reply'
    dialogVisible.value = true
    replyForm.content = ''
  } catch (error) {
    console.error('获取消息详情失败:', error)
    ElMessage.error('获取消息详情失败')
  }
}

// 提交回复
const submitReply = async () => {
  if (!replyFormRef.value) return
  
  try {
    await replyFormRef.value.validate()
    submitting.value = true
    
    await replyMessage(currentMessage.value.id, {
      content: replyForm.content
    })
    
    ElMessage.success('回复成功')
    dialogVisible.value = false
    fetchMessages()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('回复失败:', error)
      ElMessage.error('回复失败')
    }
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchMessages()
})
</script>

<style scoped>
.message-page {
  background: #fff;
  border-radius: 12px;
  padding: 32px 40px;
  min-height: calc(100vh - 140px);
  box-shadow: 0 2px 8px #f0f1f2;
  margin: -20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.empty-block {
  padding: 40px 0;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: #606266;
  margin: 16px 0 8px;
}

.empty-sub-text {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.message-detail {
  padding: 24px;
  background: #f8f9fa;
  border-radius: 8px;
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.message-time {
  color: #909399;
  font-size: 14px;
  margin-left: 12px;
}

.message-content {
  margin-bottom: 24px;
}

.message-content h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.message-content p {
  margin: 0;
  color: #606266;
  line-height: 1.8;
  font-size: 14px;
}

.message-reply {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-top: 24px;
  border: 1px solid #ebeef5;
}

.message-reply h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 15px;
  font-weight: 600;
}

.message-reply p {
  margin: 0 0 12px 0;
  color: #606266;
  line-height: 1.8;
  font-size: 14px;
}

.reply-time {
  color: #909399;
  font-size: 12px;
  display: block;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

:deep(.el-pagination) {
  margin-top: 24px;
  padding: 0;
  justify-content: flex-end;
}

:deep(.el-button--small) {
  padding: 8px 16px;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

:deep(.el-select) {
  width: 160px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 24px;
  margin-bottom: 0;
}
</style> 